//
//  LSYRuleService.m
//  LSYReader
//
//  Created by sam on 2018/4/16.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "LSYFileUtil.h"
#import "LSYRuleService.h"
#import "AFHTTPSessionManager.h"

@implementation LSYRuleService

+(instancetype)service {
    static LSYRuleService *service=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [[LSYRuleService alloc] init];
        service.rules = [service recoverFromFile];
    });
    return service;
}

-(void)getRules:(void (^)(NSArray *rules))block {
    
    [[AFHTTPSessionManager manager] GET:@"https://gitee.com/sososdk/aikanyuedu/raw/master/normal.aks" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@",downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *sites = (NSArray *)responseObject;
            NSMutableArray *rules = [NSMutableArray array];
            for (NSDictionary *ruleDict in sites) {
                LSYParseModel *model = [[LSYParseModel alloc] initWithDiction:ruleDict];
                [rules addObject:model];
            }
            self.rules = rules;
            [self saveToFile];
            if (block) {
                block(rules);
            }
        } else {
            if (block) {
                block(nil);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (block) {
            block(nil);
        }
    }];
}

- (void)saveToFile {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (![NSKeyedArchiver archiveRootObject:self.rules toFile:[LSYFileUtil ruleStorePath]]){
            [NSKeyedArchiver archiveRootObject:self.rules toFile:[LSYFileUtil ruleStorePath]];
        }
    });
}

- (NSMutableArray *)recoverFromFile {
    NSArray *rules = [NSKeyedUnarchiver unarchiveObjectWithFile:[LSYFileUtil ruleStorePath]];
    if (rules && [rules isKindOfClass:[NSArray class]]) {
        return [NSMutableArray arrayWithArray:rules];
    }
    return [NSMutableArray array];
}
@end
